﻿namespace ASB.CC.ExcelTool
{
    #region Using Directives

    using System;
    using System.Configuration;
    using System.IO;
    using System.Linq;
    using System.Threading;
    using System.Web;
    using System.Web.UI;
    using ASBCC.Database.Entity;
    using ASBCC.Database.Service;
    using BEGDC.CC.ExcelTool;
    using BEGDC.Utility.ExceptionManagement;
    using BEGDC.Utility.Extensions;
    using Excel;

    #endregion

    public class ExportEZVisitRequests
    {
        private readonly ExcelExportCommom excelExport = new ExcelExportCommom();

        private readonly string folder = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["ExportPath"]);
        private readonly string templateName = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["EZVisitTemplate2"]);

        public void Export(Page page, string searchCondition)
        {
            if (page == null)
            {
                throw  new ArgumentNullException("page");
            }

            if (searchCondition == null || searchCondition.Trim().Length == 0)
            {
                throw new ArgumentException("Search condtion cannot be empty.");
            }

            string fileName = this.Export2Excel(searchCondition);

            this.excelExport.Export2Client(page, fileName, "EZVisitRequests.xls");
        }

        private string Export2Excel(string searchCondition)
        {
            try
            {
                this.excelExport.Open(this.templateName);

                var range = this.GetRange("Applications");

                var applications = EZVisitApplicationManager.SelectByCondition(searchCondition);

                int totalApplications = applications.Count;

                int rowCount = 1;
                while (totalApplications > rowCount)
                {
                    var r = this.GetRow(range.Cells[2, 1], range.Cells[2, 25]);
                    r.Copy(Type.Missing);
                    r.Insert(XlInsertShiftDirection.xlShiftDown, false);
                    rowCount++;
                }

                int i = 1;

                foreach (EZVisitApplicationTableEntity app in applications)
                {
                    this.SetRange(range.Cells[i, 1], i);

                    string costCenter = string.Empty;

                    if (app.IsInSalesContract.GetValueOrDefault(true))
                    {
                        string contractNo = string.Empty;

                        var contracts = EZVisitContractItemManager.SelectByCondition(string.Format("AppID={0} and IsEnabled=1", app.AppID));

                        foreach (EZVisitContractItemTableEntity contract in contracts)
                        {
                            contractNo += contract.ContractNo + ",";
                            costCenter += contract.CostCenter + ",";
                        }

                        this.SetRange(range.Cells[i, 2], contractNo.Trim(','));
                    }
                    else
                    {
                        costCenter = app.CostCenter;
                    }

                    this.SetRange(range.Cells[i, 3], app.CATBranch);
                    this.SetRange(range.Cells[i, 4], app.Region);
                    this.SetRange(range.Cells[i, 5], app.Company);
                    this.SetRange(range.Cells[i, 6], costCenter.Trim(','));
                    this.SetRange(range.Cells[i, 7], app.NumberOfPerson);
                    this.SetRange(range.Cells[i, 8], app.ALAttNumberOfPerson);

                    if (app.RequestedDateFrom != null)
                    {
                        this.SetRange(range.Cells[i, 9], app.RequestedDateFrom.Value.ToString("MM/dd/yyyy"));
                    }

                    if (app.RequestedDateTo != null)
                    {
                        this.SetRange(range.Cells[i, 10], app.RequestedDateTo.Value.ToString("MM/dd/yyyy"));
                    }

                    this.SetRange(range.Cells[i, 11], app.IsDomestic.GetValueOrDefault(false) ? app.DomesticDesc: app.OverseaDesc);
                    this.SetRange(range.Cells[i, 12], app.VisitCity);
                    this.SetRange(range.Cells[i, 13], app.TotalCost);
                    this.SetRange(range.Cells[i, app.IsInSalesContract.GetValueOrDefault(true) ? 14 : 15], app.TotalCost);

                    if (app.ProviderKey != null)
                    {
                        this.SetRange(range.Cells[i, 16], app.ProviderKey.VariantEquals("Others") ? app.OthersProviderDesc : app.ProviderDesc);
                    }

                    if (!string.IsNullOrEmpty(app.ALAttNumberOfPerson))
                    {
                        string escorts = string.Empty;

                        var attendees = EZVisitALAttendeeManager.SelectByCondition("IsEnabled = 1 and AppID=" + app.AppID);

                        escorts = attendees.Cast<EZVisitALAttendeeTableEntity>().Aggregate(escorts, (current, attendee) => current + (attendee.EmployeeNameEN + ","));

                        this.SetRange(range.Cells[i, 17], escorts.Trim(','));
                    }

                    if (app.AftSubmitDate != null)
                    {
                        var feedbacks = EZVisitFeedBackManager.SelectByCondition(string.Format("AppID={0}",app.AppID));

                        if (feedbacks.Count != 0)
                        {
                            var feedback = feedbacks[0];

                            this.SetRange(range.Cells[i, 18], feedback.ScoreA);
                            this.SetRange(range.Cells[i, 19], feedback.ScoreB);
                        }
                    }

                    this.SetRange(range.Cells[i, 20], app.CODPPCheckPersonNameEN);
                    this.SetRange(range.Cells[i, 21], app.PRNO);
                    this.SetRange(range.Cells[i, 22], app.EZVisitReqNo);

                    this.SetRange(range.Cells[i, 23], app.Status ?? "Draft");
                    if (app.LGDDate != null)
                        this.SetRange(range.Cells[i, 24], app.LGDDate.Value.ToString("MM/dd/yyyy"));


                    i++;
                }

                string fileName = Path.Combine(this.folder, string.Format("EZVisitRequests{0}.xls", DateTime.Now.Ticks));

                this.excelExport.ExportAs(fileName);

                return fileName;
            }
            catch (Exception ex)
            {
                var exp = new GDCException("export_0001", ex.Message, ex.InnerException);
                throw exp;
            }
            finally
            {
                this.excelExport.Close();
            }
        }

        private void SetRange<T>(object cell, T value)
        {
            this.excelExport.MyApp.get_Range(cell, cell).Value2 = value;
        }

        private Range GetRange(string range)
        {
            return this.excelExport.MyApp.get_Range(range, Type.Missing);
        }

        private Range GetRow(object cell1, object cell2)
        {
            return this.excelExport.MyApp.get_Range(cell1, cell2).EntireRow;
        }
    }
}